#include <iostream>
#include <vector>
#include <stack>

using namespace std;

class Solution {
public:
    vector<int> asteroidCollision(vector<int>& asteroids) {
        stack<int> container;
        for (int item : asteroids) {
            // empty
            if (container.empty()) {
                container.push(item);
                continue;
            }
            // for peek and next
            if (container.top() > 0 && item < 0) {
                // case 4: + -, handle
                bool crashed = false;
                while (!container.empty() && container.top() > 0 && item < 0) {
                    int top = container.top();
                    container.pop();
                    if (abs(top) > abs(item)) {
                        // push back
                        crashed = true;
                        container.push(top);
                        break;
                    } else if (abs(top) == abs(item)) {
                        // crash
                        crashed = true;
                        break;
                    } else {
                        // handle next one
                        continue;
                    }
                }
                if (!crashed) {
                    container.push(item);
                }
            } else {
                // case 1: - +, push
                // case 2: - -, push
                // case 3: + +, push
                container.push(item);
                continue;
            }
        }
        vector<int> result;
        while (!container.empty()) {
            result.emplace_back(container.top());
            container.pop();
        }
        reverse(result.begin(), result.end());
        return result;
    }
};